package com.springapp.mvc;

import com.springapp.mvc.utils.MediaUtils;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class UploadAction {
    Logger logger = LoggerFactory.getLogger(UploadAction.class);

    @ResponseBody
    @RequestMapping(value = "/upload.json", method = RequestMethod.POST)
    public String upload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
        logger.info("上传开始————————————");
        String path = MediaUtils.save(request, file);
        logger.info("上传结束————————————");
        logger.info(path);
        return "上传成功";
    }

    @RequestMapping("download")
    public ResponseEntity<byte[]> download() throws IOException {
        String path = "F:\\04_源码目录\\trunk\\VLIAN_V2\\demo\\target\\demo\\upload\\2016\\03\\15\\82282b002b654399b25612ddf087a831.txt";
        File file = new File(path);
        HttpHeaders headers = new HttpHeaders();
//        String fileName=new String("iso-8859-1","你好.xlsx".getBytes("UTF-8"));
        String fileName = new String("你好.txt".getBytes("UTF-8"), "iso-8859-1");
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
}
